import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import axios from 'axios'
import errorCode from '@/const/errorCode'
import qs from 'qs'
import { Message } from 'element-ui'

// 从页面参数中获取企业id，租户id，应用Id
let url = window.location.href.split("#/")[0];
function getSearchString(key, url) {
    var str = url;
    var arr = [];
    if (str.split("?")[1]) {
        arr = str.split("?")[1].split("&");
    }
    var obj = {};
    // 将每一个数组元素以=分隔并赋给obj对象
    for (var i = 0; i < arr.length; i++) {
        var tmp_arr = arr[i].split("=");
        obj[decodeURIComponent(tmp_arr[0])] = decodeURIComponent(tmp_arr[1]);
    }
    return obj[key];
}
/**
 * 存储localStorage
 */
const setSession = (params = {}) => {
    let {
        name,
        content,
        type
    } = params;
    name = 'madp' + name;
    const obj = {
        dataType: typeof (content),
        content: content,
        type: type,
        datetime: new Date().getTime()
    };
    if (type) window.sessionStorage.setItem(name, JSON.stringify(obj))
    else window.localStorage.setItem(name, JSON.stringify(obj))
}

// const MadpCorpId = getSearchString("cid",url);
// const MadpTenantId = getSearchString("tid",url);
const MadpCorpId = process.env.VUE_APP_CorpId;
const MadpTenantId = process.env.VUE_APP_TenantId;

console.log('MadpCorpId', MadpCorpId)
console.log('MadpTenantId', MadpTenantId)
setSession({
    name: 'MadpCorpId',
    content: MadpCorpId,
    type: 'session'
})

// axios.defaults.timeout = 30000
// 返回其他状态吗
axios.defaults.validateStatus = function (status) {
    return status >= 200 && status <= 500 // 默认的
}
// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true
// NProgress Configuration
NProgress.configure({
    showSpinner: false
})

// HTTPrequest拦截
axios.interceptors.request.use(config => {
    NProgress.start() // start progress bar
    config.headers['Madp-Tenant-Id'] = config.headers['Madp-Tenant-Id'] || MadpTenantId; // 租户ID
    config.headers['Madp-Corp-Id'] = config.headers['Madp-Corp-Id'] || MadpCorpId; // 企业id ，为了匹配企业微信id
    if (config.method === 'get') {
        config.paramsSerializer = function (params) {
            return qs.stringify(params, { arrayFormat: 'repeat' });
        }
    }
    return config;
}, error => {
    return Promise.reject(error);
})

// HTTPresponse拦截
axios.interceptors.response.use(res => {
    NProgress.done()
    const status = Number(res.status) || 200;
    const message = res.data.msg || errorCode[status] || errorCode['default']
    if (status !== 200 || res.data.code === 1) {
        Message({
            message: message,
            type: 'error'
        })
        return Promise.reject(new Error(message));
    }

    return res;
}, error => {
    NProgress.done()
    return Promise.reject(new Error(error));
})

export default axios;
